<template>
  <div>
    <el-row type="flex" justify="center" align="middle">
      <el-steps
        :active="active"
        finish-status="success"
        align-center
        style="margin-top: 20px; width: 50%"
      >
        <el-step title="选取图片" icon="el-icon-picture" />
        <el-step title="标记图片" icon="el-icon-crop" />
        <el-step title="上传结果" icon="el-icon-upload" />
      </el-steps>
    </el-row>
    <el-divider><i class="el-icon-view" /></el-divider>
    <el-row type="flex" justify="center" align="middle">
      <!--      <el-col :span="1" />-->
      <el-col :span="7">
        <div class="sub-title">
          <span>标记历史</span>
          <el-tooltip placement="bottom" effect="light">
            <div slot="content">
              标记历史仅<el-tag type="danger" size="mini">本次浏览器访问</el-tag>期间有效，<br>在您关闭本页面或浏览器之前，请确<br>保您已上传本次标记历史~
            </div>
            <i
              class="el-icon-info"
              style="color: rgba(42, 192, 44, 0.8); margin-left: 10px"
            />
          </el-tooltip>
        </div>

        <!--        <ImageView ref="imageview" class="image-view-area" />-->
<!--        {{draggable_views}}-->
        <el-table
          :data="labelingHistory"
          :row-style="{ height: '40px' }"
          :header-cell-style="{ padding: '2px' }"
          height="600"
          border
          style="
            width: 100%;
            height: 600px;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.12),
              0 0 6px rgba(0, 0, 0, 0.04);
          "
          highlight-current-row
          @row-click="viewHistoryLabel"
        >
          <el-table-column type="expand" fixed="left">
            <template slot-scope="props">
              <el-form label-position="left" inline class="demo-table-expand">
                <el-form-item label="创建时间">
                  <span>{{
                    formatUtcTime(new Date(props.row.lastModified))
                  }}</span>
                </el-form-item>
                <el-form-item label="提交时间">
                  <span>{{ props.row.submitDate }}</span>
                </el-form-item>
              </el-form>
            </template>
          </el-table-column>
          <el-table-column label="文件名" show-overflow-tooltip>
            <template slot-scope="scope">
              <el-tag size="medium">{{ scope.row.name }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="已标" width="70" fixed="right">
            <template slot-scope="scope">
              <i class="el-icon-aim" />
              <span
                style="
                  margin-left: 10px;
                  font-size: large;
                  font-weight: bolder;
                  color: #0a76a4;
                "
              >{{ scope.row.detectionRect.length }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="65" fixed="right">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="danger"
                @click="deleteHistoryItem(scope.$index, scope.row)"
              ><i class="el-icon-delete" /></el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-col>
      <el-col :span="12">
        <div class="sub-title">
          <span v-if="!this.currentDisplayImage">标记预览</span><span
            v-if="this.currentDisplayImage"
          >您当前正在标记：<el-tag size="mini">{{
            this.currentDisplayImage.name === undefined
              ? "未选定"
              : this.currentDisplayImage.name
          }}</el-tag></span>
          <el-tooltip placement="bottom" effect="light">
            <div slot="content">
              <br><el-tag size="mini" type="danger">红色</el-tag>标记表示未指定标签类型，<el-tag
                size="mini"
                type="primary"
              >蓝色</el-tag>表示已指定。<br><span style="font-weight: bolder">TIPS:</span>选中标记框后，按下键盘<el-tag size="mini">delete</el-tag>键可以将其删除~
            </div>
            <i
              class="el-icon-info"
              style="color: rgba(42, 192, 44, 0.8); margin-left: 10px"
            />
          </el-tooltip>
        </div>
        <div ref="imagePreview" class="block">
          <el-image
            :src="base64_image_preview"
            style="display: flex; align-items: center; justify-content: center"
          >
            <div
              slot="error"
              class="image-slot"
              style="
                display: flex;
                flex-flow: column;
                align-items: center;
                justify-content: center;
              "
            >
              <span
                v-if="!show_progress"
                style="font-size: medium"
              ><i class="el-icon-picture-outline" />选取图片，开始标记</span>
              <div class="task-visual-area">
                <transition name="el-fade-in-linear">
                  <div
                    v-if="show_progress"
                    style="
                      display: flex;
                      flex-flow: column;
                      align-items: center;
                      justify-content: center;
                    "
                  >
                    <el-progress
                      :text-inside="true"
                      :stroke-width="26"
                      :percentage="processing_progress"
                      style="width: 200px"
                    />
                    <el-tag style="text-align: center">{{
                      progress_indicator
                    }}</el-tag>
                  </div>
                </transition>
              </div>
            </div>
          </el-image>
          <vue-drag-resize
            v-if="isResShow"
            v-for="(view, index) in draggable_views"
            :key="view.score"
            ref="dragViews"
            :class="view.category | filterClass"
            :style="{
              border:
                view.category === '未标记'
                  ? '2px solid #ff0000'
                  : '2px solid #0015ff',
              'background-color':
                view.category === '未标记'
                  ? 'rgba(243,8,8,0.13)'
                  : 'rgba(2,43,246,0.21)',
            }"
            :parent-limitation="true"
            :is-active="false"
            :x="view.bbox[0]"
            :y="view.bbox[1]"
            :h="view.bbox[3]"
            :w="view.bbox[2]"
            :minw="10"
            :minh="10"
            @dragstop="updateDraggableViews($event, view)"
            @resizestop="resizeDraggableViews($event, view)"
            @clicked="onActivated(view)"
          />
        </div>
      </el-col>
      <el-col :span="4">
        <div class="sub-title">
          <span>待标记队列</span>
          <el-tooltip placement="bottom" effect="light">
            <div slot="content">
              标记完成的项目将以<el-tag type="success" size="mini">绿色</el-tag>显示~
            </div>
            <i
              class="el-icon-info"
              style="color: rgba(42, 192, 44, 0.8); margin-left: 10px"
            />
          </el-tooltip>
        </div>
        <el-table
          :data="labelingQueue"
          :row-style="{ height: '40px' }"
          :header-cell-style="{ padding: '2px' }"
          height="600"
          border
          style="
            width: 100%;
            height: 600px;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.12),
              0 0 6px rgba(0, 0, 0, 0.04);
          "
          highlight-current-row
          @row-click="viewQueuedImage"
        >
          <el-table-column label="文件名" show-overflow-tooltip>
            <template slot-scope="scope">
              <el-tag
                size="medium"
                :type="scope.row.is_labeled === 1 ? 'success' : 'primary'"
              >{{ scope.row.name }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="📋" fixed="right" min-width="20%">
            <template slot-scope="scope">
              <i
                v-if="scope.row.is_labeled === 1"
                class="el-icon-success"
                style="color: rgba(42, 192, 44, 0.8); margin-left: 10px"
              />
              <i
                v-if="scope.row.is_labeled !== 1"
                class="el-icon-question"
                style="color: rgb(65, 179, 229); margin-left: 10px"
              />
            </template>
          </el-table-column>
        </el-table>
      </el-col>
    </el-row>
    <el-row type="flex" justify="center" align="left">
      <el-col :span="7">
        <div class="control-area">
          <el-tooltip content="上传标记结果" placement="top" effect="light">
            <el-button
              type="primary"
              @click="uploadLabelingResults"
            ><i class="el-icon-upload2" />上传标记结果</el-button>
          </el-tooltip>
        </div>
        <div class="summary-area">
          {{currentSummary}}
        </div>
      </el-col>
      <el-col :span="12">
        <div class="control-area">
          <!--          <el-button type="primary" icon="el-icon-folder-opened" style="margin-left: 50px;" @click="table = true">打开系统目录</el-button>-->
          <!--          <el-button type="primary" icon="el-icon-success" style="margin-left: 50px;" @click="getCrystalPos('nothing')">自动标记</el-button>-->
          <!--          <el-button type="primary" icon="el-icon-success" style="margin-left: 50px;" @click="addMarkDown">新增标记</el-button>-->
          <el-button-group>
            <el-tooltip content="打开文件目录" placement="top" effect="light">
              <el-button
                type="primary"
                @click="table = true"
              >打开文件目录</el-button>
            </el-tooltip>
            <el-tooltip content="自动标记" placement="top" effect="light">
              <el-button
                type="primary"
                @click="getCrystalPos()"
              >自动标记</el-button>

            </el-tooltip>
            <el-tooltip content="添加标记" placement="top" effect="light">
              <el-button
                type="primary"
                @click="addMarkDown"
              >添加标记</el-button>
            </el-tooltip>
            <el-tooltip content="标签完成" placement="top" effect="light">
              <el-button
                type="success"
                @click="submitLabeledImage()"
              >标签完成</el-button>
            </el-tooltip>
            <el-tooltip content="清空标记" placement="top" effect="light">
              <el-button
                type="danger"
                @click="clearMarkDown"
              >清空标记</el-button>
            </el-tooltip>
          </el-button-group>
          <div style="width: 800px"><el-divider>选择结晶类型</el-divider></div>
          <div style="margin-top: 10px">
            <el-radio-group
              v-model="currentSelectedDragView.category"
              :disabled="currentSelectedDragView.category == null"
            >
              <el-radio label="一水草酸钙结晶" border />
              <el-radio label="二水草酸钙结晶" border />
              <el-radio label="尿酸结晶" border />
              <el-radio label="磷酸铵镁结晶" border />
              <el-radio label="磷酸钙结晶" border />
              <el-radio label="胱氨酸结晶" border />
              <el-radio label="非晶型尿酸" border />
              <el-radio label="不定型磷酸钙" border />
              <el-radio label="尿酸氨" border />
              <el-radio label="尿酸钠" border />
              <el-radio label="碳酸钙" border />
            </el-radio-group>
          </div>
          <div class="labeling-section">
            <!--            <el-form v-if="showForm" ref="form" :model="markInfo" label-width="40px">-->
            <!--              <el-form-item label="标记">-->
            <!--                <el-input v-model="markInfo.name" style="width: 50%; margin-right: 10px" @keyup.delete.native="deleteSelectedView" />-->
            <!--                <el-button type="primary" icon="el-icon-success" @click="submitLabeledImage()" />-->
            <!--              </el-form-item>-->
            <!--            </el-form>-->
          </div>
          <el-tooltip
            content="反馈结果，让我们做得更好~"
            placement="right"
            effect="light"
          >
            <el-rate
              v-model="value"
              :icon-classes="iconClasses"
              show-text
              void-icon-class="icon-rate-face-off"
              :colors="['#99A9BF', '#F7BA2A', '#FF9900']"
              style="margin-top: 10px"
            />
          </el-tooltip>
        </div>
      </el-col>
      <el-col :span="4" />
    </el-row>
    <el-drawer :visible.sync="table" direction="rtl" size="70%">
      <!--      <div slot="title"><el-tag style="font-size: 15px"><i class="el-icon-folder-opened" />请选择待识别的图片文件</el-tag></div>-->
      <!--      <el-button class="submit-bt" type="primary" icon="el-icon-success" :loading="show_progress" @click="startProcessing">提交</el-button>-->
      <!--      <el-tooltip placement="bottom" effect="light">-->
      <!--        <div slot="content">请尽可能选择经过系统预处理后的图片，否则<br>可能无法达到预期效果,系统预处理的图片样本<br>路径为：insects_detection->processed_img~</div>-->
      <!--        <i class="el-icon-info" style="color: rgba(42,192,44,0.8);margin-left: 20px" />-->
      <!--      </el-tooltip>-->
      <!--      <file-view @getSelectedFile="getFilePath" />-->
      <OssFilesystem />
    </el-drawer>
  </div>
</template>
<script>
import '@/assets/custom-theme/fonts/styles.css'
import FileView from '@/views/i18n-demo/index'
import ImageView from '@/views/control-panel/components/image-view'
import VueDragResize from 'vue-drag-resize'
import { query_base64_result, query_image, query_task_progress } from '@/api/remote-search'
import LabelApi from '@/api/object-detection'
import UtilsApi from '@/api/utils'
import OssFilesystem from '@/views/file-system/oss-filesystem'
import request from '@/utils/request'
export default {
  components: { OssFilesystem, ImageView, FileView, VueDragResize },
  filters: {
    filterClass(val) {
      let str = 'draggable-view '
      switch (val) {
        case '一水草酸钙结晶':
          str += 'color1'
          break
        case '二水草酸钙结晶':
          str += 'color2'
          break
        case '尿酸结晶':
          str += 'color3'
          break
        case '磷酸铵镁结晶':
          str += 'color4'
          break
        case '磷酸钙结晶':
          str += 'color5'
          break
        case '胱氨酸结晶':
          str += 'color6'
          break
        case '不定型尿酸':
          str += 'color7'
          break
        case '不定型磷酸钙':
          str += 'color8'
          break
        default:
          break
      }
      return str
    }
  },
  data() {
    return {
      // summary
      currentSummary: null,
      crystal_type: '',
      selected_file: '',
      table: false,
      dialog: false,
      loading: false,
      processing_progress: 0,
      show_progress: false,
      progress_indicator: 'just_started...',
      progress_query_limits: 5,
      progress_query_times: 0,
      base64_image_preview: '',
      active: 0,
      value: null,
      iconClasses: ['icon-rate-face-1', 'icon-rate-face-2', 'icon-rate-face-3'],
      draggable_views: [],
      image_preview_area: {},
      markInfo: {
        name: '',
        region: '',
        date1: '',
        date2: '',
        delivery: false,
        type: [],
        resource: '',
        desc: ''
      },
      showForm: false,
      currentDisplayImage: null,
      labelingHistory: [],
      isDragViewUpdate: true,
      currentSelectedDragView: {},
      labelingQueue: [],
      isResShow: true
    }
  },
  computed: {
    imagePreviewRefresh() {
      return this.$store.state.currentSelectedFile
    },
    selectFilesRefresh() {
      return this.$store.state.downloads
    }
  },
  watch: {
    imagePreviewRefresh: function(val) {
      this.base64_image_preview = val.url
      this.currentDisplayImage = JSON.parse(JSON.stringify(val))
      this.draggable_views = []
      const already_exist = this.labelingQueue.filter(item => item.name === this.currentDisplayImage.name)
      if (already_exist.length !== 0) {
        this.$message({
          type: 'info',
          message: '该图片已添加到队列了，快去标记吧~'
        })
        this.table = false
        return
      }
      this.labelingQueue.push(this.currentDisplayImage)
      this.table = false
      this.active = 1
      // 阿里云oss API用来获取图片的大小信息，暂时用不到
      // UtilsApi.getImageInfo(val.url).then(response => {
      //   console.log(response)
      // })
    },
    selectFilesRefresh: function(val) {
      for (const valKey in val) {
        if (this.labelingQueue.filter(item => item.name === val[valKey].name).length === 0) {
          this.labelingQueue.push(val[valKey])
        }
      }
      // this.labelingQueue.push.apply(this.labelingQueue,val)
      for (const imageKey in this.labelingQueue) {
        this.labelingQueue[imageKey]['is_labeled'] = 0
      }
      // 过滤文件夹
      this.labelingQueue = this.labelingQueue.filter(item => item.size !== 0)
      sessionStorage.setItem('labelingQueue', JSON.stringify(this.labelingQueue))
      this.table = false
      this.active = 1
    }
  },
  mounted() {
    this.labelingHistory = sessionStorage.getItem('labelingHistory') == null ? [] : JSON.parse(sessionStorage.getItem('labelingHistory'))
    this.labelingQueue = sessionStorage.getItem('labelingQueue') == null ? [] : JSON.parse(sessionStorage.getItem('labelingQueue'))
    // 注册全局监听事件，监听删除键
    document.onkeydown = (e) => {
      const code = e.keyCode
      if (code == 46) { // delete
        this.deleteSelectedView()
      } else if (code === 49 || code === 97) {
        this.currentSelectedDragView.category = '一水草酸钙结晶'
      } else if (code === 50 || code === 98) {
        this.currentSelectedDragView.category = '二水草酸钙结晶'
      } else if (code === 51 || code === 99) {
        this.currentSelectedDragView.category = '尿酸结晶'
      } else if (code === 52 || code === 100) {
        this.currentSelectedDragView.category = '磷酸铵镁结晶'
      } else if (code === 53 || code === 101) {
        this.currentSelectedDragView.category = '磷酸钙结晶'
      } else if (code === 54 || code === 102) {
        this.currentSelectedDragView.category = '胱氨酸结晶'
      } else if (code === 55 || code === 103) {
        this.currentSelectedDragView.category = '不定型尿酸'
      } else if (code === 56 || code === 104) {
        this.currentSelectedDragView.category = '不定型磷酸钙'
      }
    }
  },
  methods: {
    // 上传标记结果
    uploadLabelingResults() {
      // console.log(this.$store.state.downloads)
      const totalRecords = this.labelingHistory.length
      let totalRects = 0
      let totalLabels = 0
      for (const recordKey in this.labelingHistory) {
        totalRects = totalRects + this.labelingHistory[recordKey].detectionRect.length
        const allRects = this.labelingHistory[recordKey].detectionRect
        for (const rectKey in allRects) {
          if (allRects[rectKey].category !== '未标记') {
            totalLabels = totalLabels + 1
          }
        }
      }
      if (totalLabels / totalRects < 0.9) {
        this.$alert('本次共标记【' + totalRecords + '】张图片，共计【' + totalRects + '】个标记，其中有效标记【' + totalLabels + '】个，【' + (totalRects - totalLabels) + '】个标记未指定标签类型，标记有效率【' + ((totalLabels / totalRects) * 100).toFixed(2) + '%】<【90%】，请修正无效标记后再提交吧~', '无效标记过多', {
          confirmButtonText: '确定',
          type: 'warning',
          callback: action => {
            this.$message({
              type: 'info',
              message: '有效标记率过低，已取消提交'
            })
          }
        })
        return
      }
      if (totalRecords !== 0) {
        this.$confirm('本次共标记【' + totalRecords + '】张图片，共计【' + totalRects + '】个标记，其中有效标记【' + totalLabels + '】个，【' + (totalRects - totalLabels) + '】个标记未指定标签类型，是否立即上传结果?', '感谢您！', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'success'
        }).then(() => {
          this.active = 3
          const formatedResults = this.reformateResults(this.labelingHistory)
          // console.log('formattedResults=======>', formatedResults)
          LabelApi.saveLabeledJsonFile(formatedResults).then(response => {
            if (response.ok) {
              this.$message({
                type: 'success',
                message: '结果已上传'
              })
            }
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '取消上传'
          })
        })
      } else {
        this.$message({
          type: 'info',
          message: '当前没有标记历史记录。'
        })
      }
    },
    reformateResults(results) {
      const formatedResults = []
      for (const key in results) {
        const imageLabelResult = {
          'version': '5.0.1',
          'flags': {},
          'shapes': [],
          'imagePath': '',
          'imageHeight': 0,
          'imageWidth': 0
        }
        const currentImageLabel = results[key].detectionRect
        for (const bboxKey in currentImageLabel) {
          const objRect = currentImageLabel[bboxKey]
          const shapeItem = {
            'label': 'crystal',
            'points': [],
            'group_id': null,
            'shape_type': 'rectangle',
            'flags': {}
          }
          shapeItem.points = [[objRect.bbox[0], objRect.bbox[1]], [objRect.bbox[0] + objRect.bbox[2], objRect.bbox[1] + objRect.bbox[3]]]
          shapeItem.label = objRect.category
          imageLabelResult.shapes.push(shapeItem)
        }
        imageLabelResult.imagePath = results[key].name
        formatedResults.push(imageLabelResult)
      }
      return formatedResults
    },
    // 删除标记历史中的项目
    deleteHistoryItem(index) {
      this.$confirm('确认删除该条历史?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.labelingHistory.splice(index, 1)
        sessionStorage.setItem('labelingHistory', JSON.stringify(this.labelingHistory))
        this.$message({
          type: 'success',
          message: '删除成功'
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '取消删除'
        })
      })
    },
    // 移动draggable_views后更新其坐标信息
    updateDraggableViews(newRect, view) {
      const currentViewIndex = this.draggable_views.indexOf(view)
      this.draggable_views[currentViewIndex].bbox[0] = newRect.left
      this.draggable_views[currentViewIndex].bbox[1] = newRect.top
    },
    // 拉伸draggable_views后更新其长宽信息
    resizeDraggableViews(newRect, view) {
      const currentViewIndex = this.draggable_views.indexOf(view)
      this.draggable_views[currentViewIndex].bbox[2] = newRect.width
      this.draggable_views[currentViewIndex].bbox[3] = newRect.height
    },
    // 从标记历史中选定一个项目查看或重新标记
    viewHistoryLabel(row) {
      this.isResShow = false
      this.currentDisplayImage = row
      this.base64_image_preview = row.url
      const views = JSON.parse(JSON.stringify(row.detectionRect))
      const len = this.draggable_views.length
      this.draggable_views.splice(0,len, ...views)
      console.log(this.draggable_views, '-------------------draggable_views')
      console.log(row, '-------------------row')
      console.log(this.labelingHistory, '--------------------copyOfDragViews')
      this.currentSelectedDragView.category = null
      this.currentSummary = row.summary
      setTimeout(() => {
        this.isResShow = true
      }, 0)
    },
    viewQueuedImage(row) {
      this.currentDisplayImage = row
      this.base64_image_preview = row.url
      this.draggable_views = []
      this.currentSelectedDragView.category = null
    },
    // 提交标记好的图片
    submitLabeledImage(currentDisplayImage, draggable_views) {
      let draggable_views_list = draggable_views || this.draggable_views;
      if (draggable_views_list.length === 0) {
        this.$message({
          type: 'warning',
          message: '您当前还没有进行标记'
        })
        return
      }

      const copyOfDragViews = JSON.parse(JSON.stringify(draggable_views_list))
      const currentDate = new Date()
      const submitDate = this.formatUtcTime(currentDate)
      const currentLabelingImage = currentDisplayImage || this.currentDisplayImage
      const labeledImages = this.labelingHistory.filter((e) => e.name === currentLabelingImage.name)
      const labeledQueuedImage = this.labelingQueue.filter((e) => e.name === currentLabelingImage.name)
      labeledQueuedImage[0]['is_labeled'] = 1
      const alreadyLabeled = labeledImages.length !== 0
      if (alreadyLabeled) {
        this.labelingHistory[this.labelingHistory.indexOf(labeledImages[0])]['submitDate'] = submitDate
        this.labelingHistory[this.labelingHistory.indexOf(labeledImages[0])]['detectionRect'] = copyOfDragViews
        // for (let i = 0; i < copyOfDragViews.length; i++) {
        //   console.log(copyOfDragViews[i].bbox)
        // }
      } else {
        currentLabelingImage['submitDate'] = submitDate
        currentLabelingImage['detectionRect'] = copyOfDragViews
        this.labelingHistory.push(currentLabelingImage)
      }

      sessionStorage.setItem('labelingHistory', JSON.stringify(this.labelingHistory))
      sessionStorage.setItem('labelingQueue', JSON.stringify(this.labelingQueue))
      this.$message({
        type: 'success',
        message: '结果已保存!'
      })
      this.active = 2
      // console.log('labelingHistory======>', this.labelingHistory)
    },
    formatUtcTime(datetime) {
      const date = new Date(datetime)
      return date.getFullYear() + '-' + (date.getMonth() + 1) + '-' +
        (date.getDate() < 10 ? '0' + date.getDate() : date.getDate()) + ' ' +
        (date.getHours() < 10 ? '0' + date.getHours() : date.getHours()) + ':' +
        (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()) + ':' +
        (date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds())
    },
    // 选定某个标记
    onActivated(view) {
      // this.showForm = true
      this.currentSelectedDragView = view
      // this.markInfo.name = this.currentSelectedDragView.category
    },
    // 删除某个标记
    deleteSelectedView() {
      const index = this.draggable_views.indexOf(this.currentSelectedDragView)
      this.draggable_views.splice(index, 1)
      // this.currentDisplayImage.detectionRect.splice(index,1)
    },
    // 清空所有标签
    clearMarkDown() {
      if (this.draggable_views.length === 0) {
        this.$message({
          type: 'info',
          message: '当前还未标记'
        })
      } else {
        this.$confirm('此操作将删除所有标记, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.draggable_views = []
          this.$message({
            type: 'success',
            message: '已清空!'
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '取消清空'
          })
        })
      }
    },
    // 新增标签
    addMarkDown() {
      if (this.currentDisplayImage == null) {
        this.$message({
          type: 'warning',
          message: '您还没有选中待标记的图片~'
        })
        return
      }
      const uuid = new Date().getTime() + Math.random().toString(36).substr(2)
      const newMarkDown =
      {
        'category_id': 0,
        'category': '未标记',
        'bbox': [0, 0, 50, 50],
        'score': uuid
      }
      this.draggable_views.push(newMarkDown)
    },
    // 获取尿结晶位置信息
    getCrystalPos() {
      // this.$message({
      //   type: 'warning',
      //   message: '该功能暂未上线~'
      // })

      // const arr = [
      //   [
      //     '碳酸钙',
      //     461, // x
      //     13, // y
      //     51, //
      //     124
      //   ],
      //   [
      //     '碳酸钙',
      //     46, // x
      //     13, // y
      //     514, //
      //     12
      //   ],
      //   [
      //     '碳酸钙',
      //     461, // x
      //     12, // y
      //     13, //
      //     24
      //   ],
      //   [
      //     '碳酸钙',
      //     461, // x
      //     12, // y
      //     51, // w
      //     124 // h
      //   ]
      // ]
      //
      // const res = arr.map(item => {
      //   return {
      //     bbox: [
      //       item[1],
      //       item[2],
      //       item[3],
      //       item[4]
      //     ],
      //     category: item[0]
      //   }
      // })
      // const draggable_views = res
      // const imgUrl = this.currentDisplayImage;
      // this.submitLabeledImage(imgUrl, draggable_views)
      // return

      const imgUrl = this.currentDisplayImage;
      LabelApi.getUrinaryCrystalPos({
          path: this.base64_image_preview
        }).then(response => {
          console.log('response', response);

          const draggable_views = response.result.map(item => {
          // this.draggable_views = response.result.map(item => {
            return {
              bbox: [
                item[1],
                item[2],
                item[3] - item[1] , // 宽
                item[4] - item[2] // gao
              ],
              category: item[0]
            }
          });
          imgUrl['summary'] = response.summary
          this.submitLabeledImage(imgUrl, draggable_views)
        })
    },

    // getFilePath(payload) {
    //   this.selected_file = payload
    //   this.active = 1
    //   // console.log(this.selected_file)
    // },
    startProcessing() {
      this.base64_image_preview = ''
      this.active = 1
      const supported_filetype = ['JPG', 'PNG']
      if (this.selected_file === '') {
        this.$message({
          type: 'warning',
          message: '请至少选择一张图片~'
        })
      } else if (supported_filetype.indexOf(this.selected_file.filetype) < 0) {
        this.$message({
          type: 'warning',
          message: '请选择格式为jpg/png的图片文件~'
        })
      } else {
        this.active++
        query_base64_result(this.selected_file.fullname)
          .then(response => {
            // console.log(response)
            if (response.message === 'Task submitted') {
              this.$message({
                type: 'success',
                message: '正在计算中，请稍等片刻...'
              })
              this.updateProgressBar(response.data.task_monitor)
            } else {
              this.$message({
                type: 'error',
                message: '计算失败，请检查网络设置~'
              })
            }
          })
      }
    },
    updateProgressBar(task_url) {
      const that = this
      this.show_progress = true
      query_task_progress(task_url)
        .then(response => {
          // console.log(response.data)
          that.processing_progress = parseInt(response.data.current / response.data.total * 100)
          that.progress_indicator = response.data['status']
          if (response.data['state'] !== 'PENDING' && response.data['state'] !== 'PROGRESS') {
            if ('result' in response.data) {
              // console.log(response.data['result'])
              const img_url = response.data['result']
              // that.loadingImageFromLocal(img_url)
              that.base64_image_preview = img_url
              that.$refs.imageview.get_images_list()
              that.$message({
                type: 'success',
                message: '处理成功~'
              })
              setTimeout(function() {
                that.show_progress = false
              }, 1500)
              that.active++
            } else {
              // 意料之外的事情发生
              // console.log('Ooooops...something bad happened!', response.data['result'])
              that.progress_indicator = 'Ooooops...something bad happened!, the current task returns no result~'
            }
          } else {
            setTimeout(function() {
              if (response.data['state'] === 'PENDING') {
                that.progress_query_times += 1
                // console.log(that.progress_query_times)
              }
              if (that.progress_query_times < that.progress_query_limits) {
                that.updateProgressBar(task_url)
              } else {
                that.$message({
                  type: 'error',
                  message: '任务长时间未能处理，请稍后重试...'
                })
                that.show_progress = false
                return
              }
            }, 1000)
          }
        })
    },
    loadingImageFromLocal(img_url) {
      query_image(img_url)
        .then(response => {
          // console.log(response)
          this.base64_image_preview = 'data:image/jpeg;base64,' + response.data
        })
    }
  }
}
</script>
<style lang="scss">

  .summary-area {
    text-align: center;
    font-size: 20px;
    padding: 30px;
  }

.el-drawer.rtl {
  overflow: scroll;
}
.sub-title {
  font-size: medium;
  width: 100%;
  text-align: center;
  margin-bottom: 10px;
}
.submit-bt {
  margin-left: 20px;
}
.block {
  position: relative;
  display: flex;
  margin: 0 auto;
  width: 760px;
  height: 600px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.12), 0 0 6px rgba(0, 0, 0, 0.04);
  .el-image {
    //object-fit: contain;
    width: 100%;
    height: 100%;
  }
  .draggable-view {
    //background-color: rgba(52, 138, 191, 0.2);
    border: 2px solid #57986c;
  }
  .draggable-view.active {
    background-color: rgba(250, 56, 56, 0.19);
  }
}
.image-view-area {
  //margin-top: 40px;
}
.control-area {
  display: flex;
  flex-direction: column;
  margin-top: 10px;
  justify-content: center;
  align-items: center;
  .labeling-section {
    display: flex;
    flex-direction: row;
    margin-top: 10px;
    justify-content: center;
    align-items: center;
  }
}
.task-visual-area {
  display: flex;
  justify-content: center;
  align-items: center;
}
.demo-table-expand {
  font-size: 0;
}
.demo-table-expand label {
  width: 90px;
  color: #99a9bf;
}
.demo-table-expand .el-form-item {
  margin-right: 0;
  margin-bottom: 0;
  width: 100%;
}
//.el-tag {
//   white-space: normal;
//  height: auto;
//}
.el-table__body-wrapper::-webkit-scrollbar {
  width: 8px; /*滚动条宽度*/
  height: 8px; /*滚动条高度*/
}
.el-table__body-wrapper::-webkit-scrollbar-track {
  border-radius: 10px; /*滚动条的背景区域的圆角*/
  -webkit-box-shadow: inset 0 0 6px rgba(238, 238, 238, 0.3);
  background-color: #eeeeee; /*滚动条的背景颜色*/
}
.el-table__body-wrapper::-webkit-scrollbar-thumb {
  border-radius: 10px; /*滚动条的圆角*/
  -webkit-box-shadow: inset 0 0 6px rgba(145, 143, 0143, 0.3);
  background-color: rgb(145, 143, 143); /*滚动条的背景颜色*/
}
.el-table__fixed-right {
  background: white !important;
  box-shadow: none !important;
}
.el-table__fixed {
  background: white !important;
  box-shadow: none !important;
}
.color1 {
  border-color: aquamarine !important;
}
.color2 {
  border-color: aqua !important;
}
.color3 {
  border-color: blueviolet !important;
}
.color4 {
  border-color: chartreuse !important;
}
.color5 {
  border-color: salmon !important;
}
.color6 {
  border-color: sandybrown !important;
}
.color7 {
  border-color: olivedrab !important;
}
.color8 {
  border-color: orange !important;
}
</style>
